package cn.zwx.member.svc.utils;

import cn.zwx.base.exception.BizWrapException;
import cn.zwx.member.svc.config.AuthorizationConfig;
import cn.zwx.member.svc.domain.bo.AuthorizationMemberBO;
import cn.zwx.member.svc.domain.constans.MemberConstans;
import cn.zwx.member.svc.domain.enums.MemberCodeEnum;
import cn.zwx.member.svc.domain.warp.ExceptionWrap;
import com.alibaba.fastjson2.JSON;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.MessageFormat;

/**
 * @author zhangwenxue
 */
@Component
public class AuthorizationUtil {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private AuthorizationConfig authorizationConfig;

    public AuthorizationMemberBO  authorization(String idCard,String realName) throws BizWrapException {
        // 调用接口认证
        HttpHeaders httpHeaders = new HttpHeaders();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        httpHeaders.set("Authorization", "APPCODE " + authorizationConfig.getAppcode());
        //根据API的要求，定义相对应的Content-Type
        httpHeaders.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        HttpEntity<String> httpEntity = new HttpEntity<>(MessageFormat.format("id_number={0}&name={1}",idCard, realName),httpHeaders);
        final org.springframework.http.ResponseEntity<String> mapResponseEntity = restTemplate.exchange(authorizationConfig.getHost() + authorizationConfig.getPath(),
                HttpMethod.POST, httpEntity, String.class);
        if (mapResponseEntity.getStatusCode().isError()){
            throw ExceptionWrap.wrap(MemberCodeEnum.AUTHORIZATION_ERROR);
        }
        return JSON.parseObject(mapResponseEntity.getBody(),AuthorizationMemberBO.class);
    }}
